//引入模块
const express = require("express");
const http = require("http");
const cors = require("cors");

//初始化
const app = express();
const server = http.createServer(app);

app.use(cors());

//初始化io
const io = require("socket.io")(server, {
  cors: {
    origin: "*",
    methods: ["GET", "POST", "PUT", "DELETE"],
  },
});

//服务器socket连接
io.on("connection", (socket) => {
  socket.emit("me", socket.id);

  //断开通话
  socket.on("disconnect", () => {
    socket.broadcast.emit("callEnded");
  });

  socket.on("callUser", (data) => {
    //将数据传递给通信的接听方
    const { signalData, from, name, userToCall } = data;
    io.to(userToCall).emit("callUser", {
      signal: signalData,
      name,
      from,
    });
  });
});

server.listen(5000, () => {
  console.log(`服务器正在http://localhost:${5000}端口运行...`);
});
